// pages/login/login.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    signFlag: false,
    show: false
  },

  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  changeSignFlag() {
    this.setData({
      signFlag: true
    })
  },

  // 跳转协议
  jumpAgree(e) {
    let url
    if (e.currentTarget.dataset.type == 1) { // 隐私政策协议
      url = encodeURIComponent(app.globalData.host+'/doc/privacy.html')
    } else { // 用户注册协议
      url = encodeURIComponent(app.globalData.host+'/doc/register.html')
    }
    wx.navigateTo({
      url: `/pages/webview/webview?url= ${url}`,
    })
  },

  // 随便看看 跳主页
  toHome() {
     wx.switchTab({
       url: '/pages/home/home',
     })
  },
  // 获取用户信息
  getuserinfo(e) {
    let that = this
    wx.showLoading({
        mask: true
    })
    console.log('用户信息:', JSON.parse(e.detail.rawData))
    let rawData = JSON.parse(e.detail.rawData)
    wx.login({
      success: function (res) {
        console.log('用户登录信息:', res)
        var code = res.code;
        if (code) {
          console.log('获取用户登录凭证：' + code);
          
          let shareId = wx.getStorageSync('shareId') || ''
          if (shareId) {
            wx.removeStorage({
              key: 'shareId',
            })
          }

          wx.post("/api/appletsLogin", {
            "avatarUrl": rawData.avatarUrl,
            "code": code,
            "gender": rawData.gender,
            "nickName": rawData.nickName,
            "shareId": shareId,
          }, async res => {
            wx.hideLoading()
            console.log('==== Login ===', res)
            getApp().globalData.userInfo = {...rawData, ...res.data}
            wx.setStorage({
              key:"userInfo",
              data: {...rawData, ...res.data}
            })
            getApp().globalData.token = res.data.token
            wx.setStorage({
              key:"token",
              data: res.data.token
            })
            
            let vipInfo = await wx.promiseGet(wx.api.vipUserInfo)
            if (vipInfo.code == 200) {
              getApp().globalData.vipInfo = vipInfo.data
              wx.setStorage({
                key:"vipInfo",
                data: vipInfo.data
              })
              console.info('app', getApp(), getApp().globalData.userInfo, getApp().globalData.vipInfo,)
            }

            if (res.data.mobile) {
              wx.setStorage({
                key:"signFlag",
                data: true
              })
              wx.navigateBack({
                delta: 1
              })
            } else {
              that.showPopup()
            }
          }, fail => {})
        } else {
          console.log('获取用户登录态失败：' + res.errMsg);
        }
      }
    })
  },

  // 获取用户手机号
  getPhoneNumber (e) {
    console.log('获取手机凭证：', e, e.detail.code)
    if (!e.detail.code) return
    wx.showLoading({
      mask: true
    })
    wx.get(`/api/getPhone?code=${e.detail.code}`, res => {
      wx.hideLoading()
      console.log('==== phone ===', res)
      if (res.data.mobile) {
        wx.navigateBack({
          delta: 1
        })
      } else {
        that.showPopup()
      }
    }, fail => {})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let signFlag
    try {
      signFlag = wx.getStorageSync('signFlag')
    } catch (e) {}
    if (signFlag) {
      this.setData({
        signFlag
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})